package com.webapps.tvprogram.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.graphics.Bitmap;

import com.webapps.tvprogram.data.local.LocalResourcesHandler;
import com.webapps.tvprogram.data.local.Program;
import com.webapps.tvprogram.data.local.ProgramItem;
import com.webapps.tvprogram.web.WebRetreiver;

public class XmlParsingHandler {

    private static final String tagProg = "prog";
    private static final String tagUpdated = "updated";
    private static final String tagStation = "station";
    private static final String tagProgram = "program";
    private static final String tagEntry = "entry";
    private static final String attrName = "name";
    private static final String attrIcon = "ico";
    private static final String attrDay = "day";
    private static final String attrTime = "time";
    private static final String attrLong = "long";
    private static final String attrType = "type";

    public ArrayList<Program> parseXml() throws ParserConfigurationException, SAXException, IOException {
        return parseXml(false);
    }

    public ArrayList<Program> parseXml(boolean performFullUpdate) throws ParserConfigurationException, SAXException,
            IOException {

        ArrayList<Program> programsData = new ArrayList<Program>();
        File file = new File(GlobalInfo.PATH_TO_XML_FILE + GlobalInfo.XML_FILE_NAME);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();

        DateParser dateParser = new DateParser();
        Node lastUpdatedNode = doc.getElementsByTagName(tagUpdated).item(0);
        String lastUpdatedNodeValue = lastUpdatedNode.getFirstChild().getNodeValue();
        GlobalInfo.setLastUploadDate(dateParser.parseDate(lastUpdatedNodeValue));

        NodeList stations = doc.getElementsByTagName(tagStation);
        // browse stations
        for (int s = 0; s < stations.getLength(); ++s) {

            Node currentStation = stations.item(s);
            Program currentProgram = null;
            if (currentStation.getNodeType() == Node.ELEMENT_NODE) {
                Element elem = (Element) currentStation;
                String name = elem.getAttribute(attrName);
                Bitmap programIcon = null;
                String iconLink = elem.getAttribute(attrIcon);
                if (!performFullUpdate) {
                    programIcon = new LocalResourcesHandler().getBitmapFromResource(name);
                } else {
                    programIcon = new WebRetreiver().getBitmapFromLink(name, iconLink);
                    // additionally save Bitmap to file
                    new LocalResourcesHandler().saveBitmapToFile(name, programIcon,
                            iconLink.substring(iconLink.length() - 3));
                }
                if (programIcon == null) {
                    programIcon = new LocalResourcesHandler().createUnknownBitmap();
                }
                currentProgram = new Program(name, programIcon);
                // browse programs for each day
                NodeList programs = elem.getElementsByTagName(tagProgram);
                for (int i = 0; i < programs.getLength(); ++i) {
                    Node currentProgramForDay = programs.item(i);
                    if (currentProgramForDay.getNodeType() == Node.ELEMENT_NODE) {
                        Element subElem = (Element) currentProgramForDay;
                        String date = subElem.getAttribute(attrDay);
                        // browse entries for each day
                        NodeList entries = subElem.getElementsByTagName(tagEntry);
                        for (int j = 0; j < entries.getLength(); ++j) {
                            Node currentEntry = entries.item(j);
                            String entryName = currentEntry.getFirstChild().getNodeValue();
                            if (currentEntry.getNodeType() == Node.ELEMENT_NODE) {
                                Element subSubElem = (Element) currentEntry;
                                String time = subSubElem.getAttribute(attrTime);
                                // String length =
                                // subSubElem.getAttribute(attrLong).;
                                String type = subSubElem.getAttribute(attrType);
                                ProgramItem program = new ProgramItem(entryName, dateParser.parseDate(date, time));
                                program.setType(type);
                                program.setLength(1);
                                currentProgram.addProgramItem(program);
                            }
                        }
                    }
                }
            }
            if (currentProgram != null) {
                programsData.add(currentProgram);
            }
        }
        return programsData;

    }

}
